import { AfterViewInit, Component, OnInit, TemplateRef } from '@angular/core';
import { FormControl, UntypedFormBuilder, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzTableQueryParams } from 'ng-zorro-antd/table';
import { Consts } from 'src/app/consts/consts';
import { ClientQueryParam } from 'src/app/models/param/client-query.param';
import { ClientDto } from 'src/app/models/sys/client.dto';
import { ApiService } from 'src/app/services/api.service';
import { EditMode } from 'src/app/models/enums/edit-mode.enum';
import { ContentHeaderService } from 'src/app/services/content-header.service';
import { BehaviorSubject } from 'rxjs';

const CLIENT_ID = 'clientId';
const CLIENT_NAME = 'clientName';

@Component({
  selector: 'app-clients',
  templateUrl: './clients.component.html',
  styleUrls: ['./clients.component.less']
})
export class ClientsComponent implements OnInit, AfterViewInit {
  modeSubject = new BehaviorSubject<{ mode: EditMode, client?: ClientDto }>({mode: EditMode.ADD, client: undefined });
  
  // Search fields
  searchForm!: UntypedFormGroup;
  pageIndex = 1;
  pageSize = 15;
  total = 0;
  submitted = false;

  // table list
  clients: ClientDto[] = [];

   // 对话框title
   editTitle?: string;
   clientName?: string;

   // 详情
   clientSubject = new BehaviorSubject<ClientDto>(new ClientDto());

  constructor(private _api: ApiService,
    private _fb: UntypedFormBuilder,
    private _modal: NzModalService,
    private _messageService: NzMessageService,
    private _contentHeader: ContentHeaderService) {
  }

  ngAfterViewInit(): void {
    setTimeout(() => {
      this._contentHeader.header.next('客户端管理');
    });
  }

  ngOnInit(): void {
    this.createSearchForm();
    this.onSearch();  
  }

  // 创建搜索表单
  createSearchForm() {
    this.searchForm = this._fb.group({});
    this.searchForm.addControl(CLIENT_ID, new UntypedFormControl('', [Validators.maxLength(20)]));
    this.searchForm.addControl(CLIENT_NAME, new UntypedFormControl('', [Validators.maxLength(20)]));
  }

  onSearch() {
    this.submitted = true;
    if (!this.searchForm.valid) {
      return;
    }

    this.resetPage();
    this.doSearch();
  }

  doSearch() {
    const param = new ClientQueryParam();
    param.clientId = this.searchForm.get(CLIENT_ID)?.value;
    param.clientName = this.searchForm.get(CLIENT_NAME)?.value;

    this._api.getClientList(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this.clients = resp.data ?? [];
        this.total = resp.total;

        this.submitted = false;
      }
    });
  }

  get fm() {
    return this.searchForm.controls;
  }

  // 重置搜索框
  onReset() {
    this.searchForm.get(CLIENT_ID)?.setValue(undefined);
    this.searchForm.get(CLIENT_NAME)?.setValue(undefined);
    this.submitted = false;
  }

  // 弹出新建对话框
  onCreate(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>) {
    this.editTitle = '创建客户端';
    this.clientName = undefined;

    console.log('create ...')
    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('client added');
      }
    });

    this.modeSubject.next({mode: EditMode.ADD, client: undefined});
  }

  // 弹出编辑对话框
  onUpdate(client: ClientDto, tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>) {
    this.editTitle = '编辑客户端';
    this.clientName = client.clientName;

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('client added');
      }
    });

    this.modeSubject.next({mode: EditMode.EDIT, client: client});
  }

  onDetail(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, client: ClientDto) {
    this.clientName = client.clientName;

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('product updated');
      }
    });

    this.clientSubject.next(client);
  }

  // Table删除客户操作
  handleDelete(id: string) {
    this._api.deleteClient(id).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this._messageService.info("删除客户端成功!");
        this.onSearch();
      } else {
        this._messageService.warning("删除客户端失败：" + resp.message);
      }
    });
  }

  onPageParamChange(params: NzTableQueryParams) {
    this.submitted = true;
    if (!this.searchForm.valid) {
      return;
    }

    this.pageIndex = params.pageIndex;
    this.pageSize = params.pageSize;
    this.doSearch();
  }

  onAddClientEvent(result: boolean) {
    this._modal.closeAll();

    if (result) {
      this.onSearch();
    }
  }

  onDetailEvent(result: boolean) {
    this._modal.closeAll();
    console.log(`${result}`);
  }

  resetPage() {
    this.pageIndex = 1;
    this.pageSize = 10;
  }
}
